package com.pangdonghao.internationalizationdemo.config;


import com.pangdonghao.internationalizationdemo.core.response.Meta;
import com.pangdonghao.internationalizationdemo.core.response.Result;
import com.pangdonghao.internationalizationdemo.core.response.StatusCode;
import com.pangdonghao.internationalizationdemo.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理
 * @author pangdonghao
 * @csdn https://blog.csdn.net/pangdongh
 * @version 1.0
 * @createDate 2019/08/19 13:52
 */
@ControllerAdvice
@RestController
@RequestMapping( value = "/error")
@Slf4j
public class ControllerException {


    @RequestMapping(value = "/401" ,produces = {"application/json;charset=UTF-8"})
    public Result forbidden401(HttpServletResponse response) {
        response.setStatus(200);
        System.out.println("401");
        return Result.error(StatusCode.UNAUTHORIZED);
    }


    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result defaultException(Exception e) {
        log.error("系统内部错误", e);
        return Result.error(StatusCode.INTERNAL_SERVER_ERROR);
    }

    /**
     * 业务异常.
     * @param ex
     * @return
     */
    @ExceptionHandler(BaseException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Result businessException(BaseException ex) {
        Meta meta = ex.handler();
        log.error("业务异常 => {}", meta.getMsg());
        return Result.error(meta);
    }
}